/**
 * Created by YHQ on 2016-03-22.
 */
angular.module('hyt.userCtrl',[])
    //用户登录
    .controller("LoginCtrl",function($scope,ENV,$state,$resource,User,Storage,$ionicLoading,Regist,$stateParams,$ionicPopup,$window){

        $scope.user={
            sjhm:'',
            pwd:'',
            jzmm:''
        };
        if ($stateParams.lxdh!=''){
            $scope.user.sjhm=$stateParams.lxdh;
        }else if(Storage.get('user')!=null){
            $scope.user=Storage.get('user');
        }
        $scope.changeNum=function(val) {
            $scope.user.pwd='';
            if (val.length == 11) {
                Regist.checkExist($scope.user.sjhm);
                $scope.$on('Check.CheckUser', function() {
                    var result = Regist.getResult();
                    console.log(result);
                    //手机号重复
                    if (result.ACTION_INFO.sjhcf == false&&result.ACTION_INFO.sjdqr==''&&result.ACTION_INFO.sfwlgs==1) {
                        $state.go('verification',{sjhm:val,sfwlgs:result.ACTION_INFO.sfwlgs});
                    } else {

                    }
                })
            }
        };

        $scope.kfdh='400-027-2456';
        $scope.callPhone = function (mobilePhone) {
            var confirmPopup = $ionicPopup.confirm({
                title:mobilePhone,
                okText:'呼叫',
                cancelText:'取消'
            });
            confirmPopup.then(function(res) {
                if (res) {
                    $window.location.href = "tel:" + mobilePhone;
                }else {

                }
            });

        };
        //跳转到忘记密码界面
        $scope.gotoPwd=function(){
            $state.go('forgetpwd');
        };

        //用户登录
        $scope.signIn=function(){
            if ($scope.user.jzmm==true){
                Storage.set('user',$scope.user);
            }else {
                Storage.set('user',null);
            }
            //判断网络连接
            document.addEventListener("deviceready", onDeviceReady, false);
            function onDeviceReady() {
                checkConnection();
            }
            function checkConnection() {
                var networkState = navigator.connection.type;

                var states = {};
                states[Connection.UNKNOWN]  = 'Unknown connection';
                states[Connection.ETHERNET] = 'Ethernet connection';
                states[Connection.WIFI]     = 'WiFi connection';
                states[Connection.CELL_2G]  = 'Cell 2G connection';
                states[Connection.CELL_3G]  = 'Cell 3G connection';
                states[Connection.CELL_4G]  = 'Cell 4G connection';
                states[Connection.CELL]     = 'Cell generic connection';
                states[Connection.NONE]     = 'No network connection';

                if(states[networkState]=='No network connection'){
                    $ionicLoading.show({
                        noBackdrop: true,
                        template: "请检查网络连接!",
                        duration: 1500
                    });
                }
            }
            if($scope.user.sjhm==""){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "请输入手机号码",
                    duration: 1500
                });
            }else  if($scope.user.pwd==""){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "请输入密码",
                    duration: 1500
                });
            }else {
                User.login($scope.user.sjhm,$scope.user.pwd,"");
            }
        };

        //广播登录结果
        $scope.$on('User.loginUpdated', function() {

            var result = User.getResult();
            console.log(result);

            if(result.ACTION_RETURN_CODE=='100006'){//登陆失败
                //    alert(userRel.message);
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "用户名不存在",
                    duration: 1500
                });
            }else if(result.ACTION_RETURN_CODE=='000002'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "账户名重复",
                    duration: 1500
                });
                //Storage.set(storageKey,userRel);
                //$state.go('fhkd');  //路由跳转
            }else if(result.ACTION_RETURN_CODE=='000003'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "账户名或者密码错误",
                    duration: 1500
                });
            }else if(result.ACTION_RETURN_CODE=='100010'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "账号异常，请联系客服",
                    duration: 1500
                });
            }else if(result.ACTION_RETURN_CODE=='000004'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "停用的用户",
                    duration: 1500
                });
            }else if(result.ACTION_RETURN_CODE=='100009'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "请验证手机号",
                    duration: 1500
                });
                Regist.checkExist($scope.user.sjhm);
                $scope.$on('Check.CheckUser', function() {
                    var result = Regist.getResult();
                    console.log(result);
                    //手机号重复
                    if (result.ACTION_INFO.sjhcf == false&&result.ACTION_INFO.sjdqr==''&&result.ACTION_INFO.sfwlgs==1) {
                        $state.go('verification',{sjhm:$scope.user.sjhm,sfwlgs:result.ACTION_INFO.sfwlgs});
                    } else {

                    }
                })
            } else if(result.ACTION_RETURN_CODE=='000000'){
                Storage.set('dw_id',result.ACTION_INFO.user.dw_id);
                Storage.set('zd_id',result.ACTION_INFO.user.zd_id);
                Storage.set('zdmc',result.ACTION_INFO.user.zdmc);
                Storage.set('zsxm',result.ACTION_INFO.user.zsxm);
                Storage.set('yh_id',result.ACTION_INFO.user.yh_id);
                Storage.set('lxdh',result.ACTION_INFO.user.lxdh);
                Storage.set('yhmc',result.ACTION_INFO.user.yhmc);
                Storage.set('bmmc',result.ACTION_INFO.user.bmmc);
                Storage.set('dwmc',result.ACTION_INFO.user.dwmc);
                Storage.set('bm_id',result.ACTION_INFO.user.bm_id);
                Storage.set('sid',result.SID);
                Storage.set('sfwlgs',result.ACTION_INFO.user.sfwlgs);
                Storage.set('user_id',result.uSER_ID);
                Storage.set('isCheckApk',false);
                Storage.set('version_no',ENV.version_no);
                Storage.set('zddh',result.ACTION_INFO.zddh);
                var fwqdz=result.ACTION_INFO.user.fwqdz+"/call.nut";
                Storage.set('url',result.ACTION_INFO.user.fwqdz);
                Storage.set('fwqdz',fwqdz);
                Storage.set('isLogin',true);
                $state.go('menu');  //路由跳转
            }
            else {
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "未知的用户",
                    duration: 1500
                });
                console.log(result);
            }
        });
        $scope.clearUser=function(){
            Storage.remove('dw_id');
            Storage.remove('zsxm');
            Storage.remove('yh_id');
            Storage.remove('lxdh');
            Storage.remove('yhmc');
            Storage.set('isLogin',false);
        }

    })
    //验证手机号
    .controller('VerificationCtrl',function($scope,$ionicLoading,$state,Storage,$interval,$stateParams,VerificationFactory,Regist){
        $scope.user={
            lxdh:$stateParams.sjhm,
            yzm:''
        };
        //设置验证码倒计时
        var timePromise=undefined;
        $scope.paracont = "获取验证码";
        $scope.timmer=function() {
            $scope.paraevent = true;
            var second=60;
            $("#yzmBtn").attr("disabled", true);
            timePromise = $interval(function(){
                if(second<=0){
                    $interval.cancel(timePromise);
                    timePromise = undefined;
                    second = 60;
                    $("#yzmBtn").attr("disabled", false);
                    $scope.paracont = "重发验证码";
                    $scope.paraevent = true;
                }else{
                    $("#yzmBtn").attr("disabled", true);
                    $scope.paracont = second + "秒后可重发";
                    second--;
                }
            },1000,100);
        };
        $scope.clearTimmer=function(){
            $interval.cancel(timePromise);
        };
        //获取验证码
        $scope.getYzmcode=function(){
            $scope.timmer();
            Regist.getYzmCode($scope.user.lxdh);
        }
        $scope.verification=function(){
            VerificationFactory.verification($scope.user.lxdh,$stateParams.sfwlgs,$scope.user.yzm);
        };
        $scope.$on('Verification.yzm',function(){
            var result=VerificationFactory.getResult();
            console.log(result);
            if(result.ACTION_INFO.result==false){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "验证失败",
                    duration: 1500
                });
            }else if(result.ACTION_RETURN_CODE=='100008'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "验证码错误",
                    duration: 1500
                });
            }else if(result.ACTION_RETURN_CODE=='000000'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "验证通过",
                    duration: 1500
                });
                $state.go('login',{lxdh:$scope.user.lxdh});
            }
        });
        $("#verificate").attr("disabled", true);
        $scope.isNull=function(){
            if($scope.user.yzm!=''){
                $("#verificate").attr("disabled", false);
            }
            else {
                $("#verificate").attr("disabled", true);
            }
        }
    })
    //用户注册
    .controller("RegistCtrl",function($scope,ENV,$state,$resource,Regist,Storage,$ionicLoading,$interval,Storage){
        $scope.user= {
            sjhm: '',
            pwd: '',
            yzm: '',
            yhmc: '',
            dwmc: '',
            yhlx: ''
        };

        $("#regist").attr("disabled", true);
        //手机号为11位，获取验证码按钮才有效
        $("#yzmBtn").attr("disabled", true);
        $scope.changeYz=function(){
            //判断手机号是否合法
            if($scope.user.sjhm.length==11&&$scope.user.sjhm&& /^1[3|4|5|7|8]\d{9}$/.test($scope.user.sjhm)){
                //alert(true);
                Regist.checkExist($scope.user.sjhm);
                $scope.$on('Check.CheckUser', function() {
                    var result = Regist.getResult();
                    console.log(result);
                    //手机号重复
                    if (result.ACTION_INFO.sjhcf == false&&result.ACTION_INFO.sjdqr==1) {
                        $ionicLoading.show({
                            noBackdrop: true,
                            template: "该手机号已存在，请直接登录！",
                            duration: 1500
                        });
                    } else {
                        $("#yzmBtn").attr("disabled", false);
                    }
                })
            }else {
                //alert(false);
                $("#yzmBtn").attr("disabled", true);
            }
        };

        $scope.changeNum=function(){
            //判断输入框是否都输入完
            if($scope.user.pwd!=""&&$scope.user.yzm!=""&&$scope.user.sjhm!=""){
                Regist.checkExist2($scope.user.sjhm);
                $scope.$on('Check2.CheckUser', function() {
                    var result = Regist.getResult2();
                    console.log(result);
                    //手机号重复
                    if (result.ACTION_INFO.sjhcf == false&&result.ACTION_INFO.sjdqr==1) {
                        $("#regist").attr("disabled", true);
                    } else {
                        $("#regist").attr("disabled", false);
                    }
                })
            }else {
                $("#regist").attr("disabled", true);
            }
        };


        //设置验证码倒计时
        var timePromise=undefined;
        $scope.paracont = "获取验证码";
        $scope.timmer=function() {
          $scope.paraevent = true;
          var second=60;
          $("#yzmBtn").attr("disabled", true);
          timePromise = $interval(function(){
            if(second<=0){
              $interval.cancel(timePromise);
              timePromise = undefined;
              second = 60;
              $("#yzmBtn").attr("disabled", false);
              $scope.paracont = "重发验证码";
              $scope.paraevent = true;
            }else{
              $("#yzmBtn").attr("disabled", true);
              $scope.paracont = second + "秒后可重发";
              second--;
            }
          },1000,100);
        };

        $scope.clearTimmer= function () {
            $interval.cancel(timePromise);
        };
        //注册
        $scope.check=function(){
            var code=$scope.user.pwd;
            Regist.regist($scope.user.sjhm,code,$scope.user.yzm,6);
        };

        //点击按钮获取验证码
        $scope.getCode=function(){
            $scope.timmer();
            Regist.getYzmCode($scope.user.sjhm);
        };

        //注册
        $scope.$on('Regist.RegistUser',function(){
            var user=Regist.getUser();
            console.log(user);
            //判断验证码是否正确
            if(user.ACTION_RETURN_CODE=='100008'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "验证码错误！",
                    duration: 1500
                });
            }else if(user.ACTION_RETURN_CODE=='000003'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "注册失败！",
                    duration: 1500
                });
            }else{
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "注册成功！",
                    duration: 1500
                });
                //Storage.set("isLogin",true);
                //Storage.set('lxdh',result.ACTION_INFO.lxdh);
                //Storage.set('bm_id',result.ACTION_INFO.bm_id);
                //Storage.set('bmmc',result.ACTION_INFO.bmmc);
                //Storage.set('dw_id',result.ACTION_INFO.dw_id);
                //Storage.set('yh_id',result.ACTION_INFO.yh_id);
                //Storage.set('dwmc',result.ACTION_INFO.dwmc);
                //Storage.set('zd_id',result.ACTION_INFO.zd_id);
                //Storage.set('zdmc',result.ACTION_INFO.zdmc);
                $state.go('login');
            }
            $scope.clearTimmer;
        })
    })

    //忘记密码
    .controller('ForgetPwdCtrl',function($scope,ForgetPwdFactory,$ionicLoading,$state,Storage,$interval,Regist){
        $scope.user={
            lxdh:'',
            pwd:'',
            yzm:''
        };
        $("#forgetPwd").attr("disabled", true);
        //手机号为11位，获取验证码按钮才有效
        $("#yzmBtn").attr("disabled", true);
        $scope.changeNum=function(val){
            if(val.length==11&&val&& /^1[3|4|5|7|8]\d{9}$/.test(val)){
                //alert(true);
                Regist.checkExist(val);
                $scope.$on('Check.CheckUser', function() {
                    var result = Regist.getResult();
                    console.log(result);
                    //手机号重复
                    if (result.ACTION_INFO.sjhcf == true) {
                        $ionicLoading.show({
                            noBackdrop: true,
                            template: "该手机号未注册！",
                            duration: 1500
                        });
                    } else {
                        $("#yzmBtn").attr("disabled", false);
                    }
                })
            }else {
                //alert(false);
                $("#yzmBtn").attr("disabled", true);
            }
        };
        $scope.isNull=function(){
            if($scope.user.lxdh!=''&&$scope.user.yzm!=''&&$scope.user.pwd!=''){
                $("#forgetPwd").attr("disabled", false);
            }
            else {
                $("#forgetPwd").attr("disabled", true);
            }
        };
        //设置验证码倒计时
        var timePromise=undefined;
        $scope.paracont = "获取验证码";
        function timmer() {
            $("#yzmBtn").attr("disabled", true);
            $scope.paraevent = true;
            var second=60;
            timePromise = $interval(function(){
                if(second<=0){
                    $interval.cancel(timePromise);
                    timePromise = undefined;
                    second = 60;
                    $("#yzmBtn").attr("disabled", false);
                    $scope.paracont = "重发验证码";
                    $scope.paraevent = true;
                }else{
                    $("#yzmBtn").attr("disabled", true);
                    $scope.paracont = second + "秒后可重发";
                    second--;
                }
            },1000,100);
        }
        $scope.cleanTimmer=function(){
            $interval.cancel(timePromise);
        };
        //判断用户是否存在
        var sfwlgs;
        $scope.updatePwd=function(){
            ForgetPwdFactory.checkUser($scope.user.lxdh);
            //验证用户是否存在
            $scope.$on('CheckF.CheckUser',function(){
                var userInfo=ForgetPwdFactory.getUser();
                sfwlgs=userInfo.ACTION_INFO.sfwlgs;
                if(userInfo.ACTION_RETURN_CODE=='100006'){
                    $ionicLoading.show({
                        noBackdrop: true,
                        template: "该用户不存在",
                        duration: 1500
                    });
                }
                else {
                    //重置密码
                    ForgetPwdFactory.update($scope.user.pwd,$scope.user.yzm,$scope.user.lxdh,sfwlgs);
                    $scope.$on('Update.UpdatePwd',function(){
                        var result=ForgetPwdFactory.getResult();
                        if($scope.user.pwd!=''){
                            if(result.ACTION_RETURN_CODE=='100008'){
                                $ionicLoading.show({
                                    noBackdrop: true,
                                    template: "验证码错误，密码重置失败",
                                    duration: 1500
                                });
                            }else{
                                $ionicLoading.show({
                                    noBackdrop: true,
                                    template: "重置成功",
                                    duration: 1500
                                });
                                Storage.set("isLogin",true);
                                Storage.set('lxdh',result.ACTION_INFO.lxdh);
                                Storage.set('pwd',result.ACTION_INFO.pwd);
                                $state.go('login');
                                $scope.cleanTimmer();
                            }
                        }else {
                            $ionicLoading.show({
                                noBackdrop: true,
                                template: "请输入密码",
                                duration: 1500
                            });
                        }
                    })
                }
            });
        };
        //获取验证码
        $scope.getYzmcode=function(){
            timmer();
            ForgetPwdFactory.getYzm($scope.user.lxdh);
        }
    })
    //修改密码
    .controller('ChangePwdCtrl',function($scope,ForgetPwdFactory,$ionicLoading,$state,Storage,$interval){
        var lxdh=Storage.get('lxdh');
        $scope.user={
            lxdh:lxdh,
            pwd:'',
            yzm:''
        };
        $("#forgetPwd").attr("disabled", true);

        $scope.isNull=function(){
            if($scope.user.yzm!=''&&$scope.user.pwd!=''){
                $("#forgetPwd").attr("disabled", false);
            }
            else {
                $("#forgetPwd").attr("disabled", true);
            }
        }
        //设置验证码倒计时
        var timePromise=undefined;
        $scope.paracont = "获取验证码";
       function timmer() {

            $scope.paraevent = true;
            var second=60;
            timePromise = $interval(function(){
                if(second<=0){
                    $interval.cancel(timePromise);
                    timePromise = undefined;
                    second = 60;
                    $("#yzmBtn").attr("disabled", false);
                    $scope.paracont = "重发验证码";
                    $scope.paraevent = true;
                }else{
                    $("#yzmBtn").attr("disabled", true);
                    $scope.paracont = second + "秒后可重发";
                    second--;
                }
            },1000,100);
        };
        $scope.clearTimmer= function () {
            $interval.cancel(timePromise);
        };
        //验证用户是否存在
        $scope.$on('Checkxiu.CheckUser',function(){
            var userInfo=ForgetPwdFactory.getUserxiu();

            if(userInfo.ACTION_RETURN_CODE=='100006'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "该用户不存在",
                    duration: 1500
                });
            }
            else {
                //修改密码
                ForgetPwdFactory.updatexiu($scope.user.pwd,$scope.user.yzm,$scope.user.lxdh);
                $scope.$on('Updatexiu.UpdatePwd',function(){
                    var result=ForgetPwdFactory.getResultxiu();
                    if($scope.user.pwd!=''){
                        if(result.ACTION_RETURN_CODE=='100008'){
                            $ionicLoading.show({
                                noBackdrop: true,
                                template: "验证码错误，密码修改失败",
                                duration: 1500
                            });
                        }else{
                            $ionicLoading.show({
                                noBackdrop: true,
                                template: "修改成功",
                                duration: 1500
                            });
                            Storage.remove('sid');
                            Storage.set("isLogin",true);
                            Storage.set('lxdh',result.ACTION_INFO.lxdh);
                            Storage.set('pwd',result.ACTION_INFO.pwd);
                            $state.go('login');
                        }
                        $scope.clearTimmer();
                    }else {
                        $ionicLoading.show({
                            noBackdrop: true,
                            template: "请输入密码",
                            duration: 1500
                        });
                    }
                })
            }
        });
        //判断用户是否存在
        $scope.updatePwd=function(){
            ForgetPwdFactory.checkUserxiu($scope.user.lxdh);
        };
        //获取验证码
        $scope.getYzmcode=function(){
            timmer();
            ForgetPwdFactory.getYzmxiu($scope.user.lxdh);
        }
    })

    .controller('SettingCtrl',function($scope,$ionicPopup,$state,CheckAPKFactory,Storage,GenCydhFactory,$ionicLoading,$ionicActionSheet,$timeout,$cordovaAppVersion,$cordovaFileOpener2,$cordovaFileTransfer,ENV,$ionicHistory,ZdqhFactory,User,$window){
        var sid=Storage.get('sid');
        var user_id=Storage.get('user_id');
        var yh_id=Storage.get('yh_id');
        var zd_id=Storage.get('zd_id');
        var dw_id=Storage.get('dw_id');
        var sfwlgs=Storage.get('sfwlgs');
        $scope.zdmc=Storage.get('zdmc');
        $scope.zd_id=zd_id;
        $scope.bbh=ENV.version;
        $scope.fwqbs=ENV.fwqbs;
        if (sid==null){
            $state.go("login");
        }
        if(sfwlgs==0){
            $("#qhzd").removeClass("show").addClass("hide");
            $("#cydhzdsc").removeClass("show").addClass("hide");
            $("#dyj").removeClass("show").addClass("hide");
        }
        GenCydhFactory.checkBox(sid,user_id,yh_id,zd_id);
        $scope.$on('CheckBox.Cydh',function(){
            var checkBox=GenCydhFactory.getCheckBox();
            if(checkBox.ACTION_INFO.result==false){
                $("#toggleBtn").addClass("hide");
            }
            else {
                $("#settingCydh").addClass("hide");
            }
        });
        ZdqhFactory.zdList(sid,yh_id,dw_id,user_id,zd_id);
        $scope.$on('ZdqhData',function(){
            $scope.zdList=ZdqhFactory.getResult();

        });
        $("#qhzd").change(function(e) {
            Storage.set('bm_id',$("#qhzd option:selected").val());
            Storage.set('zd_id',$("#qhzd option:selected").val());
            Storage.set('zdmc',$("#qhzd option:selected").text());
            Storage.set('bmmc',$("#qhzd option:selected").text());
            $state.go('menu');
        });
        $scope.sjhm=Storage.get('lxdh');
        $scope.zsxm=Storage.get('zsxm');
        $scope.cyd={
            autoCydh:'',
            type:''
        };

        $("#toggleBtn").change(function(){
            if($scope.cyd.autoCydh==true){
                $scope.cyd.type='1';
            }else{
                $scope.cyd.type='0';
            }
            GenCydhFactory.autoCydh(sid,user_id,yh_id,zd_id,dw_id,$scope.cyd);
        });

        $scope.$on('Save.AutoCydh',function(){
            if($scope.cyd.type=='1'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "承运单号自动生成已开启",
                    duration: 1500
                });
            }else if($scope.cyd.type=='0'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "承运单号自动生成已关闭",
                    duration: 1500
                });
            }else{
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "承运单号自动生成修改失败",
                    duration: 1500
                });
            }
        });

        //初始化toggleButton
        GenCydhFactory.check(sid,user_id,yh_id,zd_id,dw_id);
        $scope.$on('Check.Cydh',function(){
            var result=GenCydhFactory.getResult();
            console.log(result);
            var list=result.ACTION_INFO.RESULT_LIST;
            if(list.length>0){
                var cn=list[0].cydh_add_type;
                if(cn=='1'){
                    $scope.cyd.autoCydh=true;
                }else {
                    $scope.cyd.autoCydh=false;
                }
            }
        });
        //拨号
        $scope.kfdh='400-027-2456';
        $scope.callPhone = function (mobilePhone) {
            var confirmPopup = $ionicPopup.confirm({
                title:mobilePhone,
                okText:'呼叫',
                cancelText:'取消'
            });
            confirmPopup.then(function(res) {
                if (res) {
                    $window.location.href = "tel:" + mobilePhone;
                }else {

                }
            });

        };
        //清除缓存
        //$scope.clean = function() {
        //    var confirmPopup = $ionicPopup.confirm({
        //        template: '确定清除缓存吗?清除缓存后，所有图片、数据都需要重新加载！',
        //        okText:'确定',
        //        cancelText:'取消'
        //    });
        //    confirmPopup.then(function(res) {
        //
        //    });
        //};
        //退出登录
        $scope.exit=function(){
            var confirmPopup = $ionicPopup.confirm({
                title:'退出登录',
                template: '您确定要退出吗？',
                okText:'确定',
                cancelText:'取消'
            });
            confirmPopup.then(function(res) {
                if(res){
                    Storage.remove('dw_id');
                    Storage.remove('sid');
                    Storage.remove('zsxm');
                    Storage.remove('yh_id');
                    Storage.remove('lxdh');
                    Storage.remove('yhmc');
                    Storage.set('menuDatas',null);
                    $ionicHistory.clearCache();
                    $ionicHistory.clearHistory();
                    Storage.set('isLogin',false);
                    $state.go('login');
                }
                else {
                    return false;
                }
            });
        };
        //检查网络
        var networkState = navigator.connection.type;
        var states = {};
        states[Connection.UNKNOWN]  = 'Unknown connection';
        states[Connection.ETHERNET] = 'Ethernet connection';
        states[Connection.WIFI]     = 'WiFi connection';
        states[Connection.CELL_2G]  = 'Cell 2G connection';
        states[Connection.CELL_3G]  = 'Cell 3G connection';
        states[Connection.CELL_4G]  = 'Cell 4G connection';
        states[Connection.CELL]     = 'Cell generic connection';
        states[Connection.NONE]     = 'No network connection';
        var version_no=ENV.version_no;
        var download_url;

        var content;
        CheckAPKFactory.queryContent(sid,user_id,yh_id,dw_id);
        $scope.$on('UpdateContent.APK',function(){
            var result=CheckAPKFactory.getResultContent();
            if(result.ACTION_RETURN_CODE=='000000'){
                content=result.ACTION_INFO.RESULT_LIST[0].gxnr;
            }
        });
        //检测更新
        CheckAPKFactory.checkQuery(version_no,sid,user_id,yh_id,dw_id);
        $scope.$on('UpdateQuery.APK',function(){
            var resultQ=CheckAPKFactory.getResultQuery();
            if(resultQ.ACTION_RETURN_CODE=='000000'){
                if(resultQ.ACTION_INFO.TOTAL>0){
                    $scope.cn=resultQ.ACTION_INFO.TOTAL;
                }
            }
        });

        $scope.checkAPK=function(){
            if(states[networkState]=='No network connection'){
                $ionicLoading.show({template: '无网络连接', noBackdrop: true, duration: 2000});
            }else {
                CheckAPKFactory.check(version_no,sid,user_id,yh_id,dw_id);
            }
        };
        $scope.$on('Update.APK',function(){
            var result=CheckAPKFactory.getResult();
            if(result.ACTION_RETURN_CODE=='000000'){
                if(result.ACTION_INFO.TOTAL>0){
                    download_url=result.ACTION_INFO.RESULT_LIST[0].download_url;
                    showUpdateConfirm();
                }else {
                    $ionicLoading.show({
                        noBackdrop: true,
                        template: "当前已是最新版本",
                        duration: 1500
                    });
                }
            }
        });
        //function checkUpdate() {
        //    //获取版本
        //    $cordovaAppVersion.getAppVersion().then(function (version) {
        //        //如果本地与服务端的APP版本不符合
        //        if (version != supversion) {
        //            showUpdateConfirm();
        //        }
        //    }).error(function (data, status, headers, config) {
        //        $ionicLoading.show({template: '读取版本信息失败！', noBackdrop: true, duration: 2000});
        //    });
        //}
        // 显示是否更新对话框
        function showUpdateConfirm() {
            var confirmPopup = $ionicPopup.confirm({
                title: '版本升级',
                template: content, //从服务端获取更新的内容
                cancelText: '取消',
                okText: '升级'
            });

            confirmPopup.then(function (res) {
                if (res) {

                    if(states[networkState]=='Cell 2G connection'||states[networkState]=='Cell 3G connection'||states[networkState]=='Cell 4G connection'||states[networkState]=='Cell generic connection'){
                        var pop= $ionicPopup.confirm({
                            template: '检测到您当前使用的是流量，是否要继续下载?',
                            cancelText: '取消',
                            okText: '继续'
                        });
                        pop.then(function(res){
                            if(res){
                                $ionicLoading.show({
                                    template: "已经下载：0%"
                                });
                                var url = download_url; //可以从服务端获取更新APP的路径
                                var targetPath= "file:///storage/sdcard0/hytAndroid/hyt.apk";
                                //APP下载存放的路径，可以使用cordova file插件进行相关配置
                                var trustHosts = true;
                                var options = {};

                                $cordovaFileTransfer.download(url,targetPath,options,trustHosts).then(function (result) {
                                    // 打开下载下来的APP
                                    $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive'
                                    ).then(function () {
                                        // 成功
                                    }, function (err) {
                                        // 错误
                                    });
                                    $ionicLoading.hide();
                                }, function (err) {
                                    $ionicLoading.show({template: '下载失败！', noBackdrop: true, duration: 2000});
                                }, function (progress) {
                                    //进度，这里使用文字显示下载百分比
                                    $timeout(function () {
                                        var downloadProgress = (progress.loaded / progress.total) * 100;
                                        $ionicLoading.show({
                                            template: "已经下载：" + Math.floor(downloadProgress) + "%"
                                        });
                                        if (downloadProgress > 99) {
                                            $ionicLoading.hide();
                                        }
                                    })
                                });
                            }
                            else {
                                //放弃下载
                            }
                        })
                    }
                    else {
                        $ionicLoading.show({
                            template: "已经下载：0%"
                        });
                        var url = download_url; //可以从服务端获取更新APP的路径
                        var targetPath= "file:///storage/sdcard0/hytAndroid/hyt.apk";
                        //APP下载存放的路径，可以使用cordova file插件进行相关配置
                        var trustHosts = true;
                        var options = {};

                        $cordovaFileTransfer.download(url,targetPath,options,trustHosts).then(function (result) {
                            // 打开下载下来的APP
                            $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive'
                            ).then(function () {
                                // 成功
                            }, function (err) {
                                // 错误
                            });
                            $ionicLoading.hide();
                        }, function (err) {
                            $ionicLoading.show({template: '下载失败！', noBackdrop: true, duration: 2000});
                        }, function (progress) {
                            //进度，这里使用文字显示下载百分比
                            $timeout(function () {
                                var downloadProgress = (progress.loaded / progress.total) * 100;
                                $ionicLoading.show({
                                    template: "已经下载：" + Math.floor(downloadProgress) + "%"
                                });
                                if (downloadProgress > 99) {
                                    $ionicLoading.hide();
                                }
                            })
                        });
                    }

                } else {
                    // 取消更新
                }
            });
        }
    })

    .controller('AddPrinterCtrl',function($scope,ForgetPwdFactory,$ionicLoading,$state,Storage,$interval,$cordovaHdoitBle,PrinterFactory,$ionicHistory,$timeout){
        var sid=Storage.get('sid');
        var user_id=Storage.get('user_id');
        var yh_id=Storage.get('yh_id');
        var zd_id=Storage.get('zd_id');
        $scope.print={
            fhrcg:'',
            sfdyfhrcg:'',
            wlgscg:'',
            sfdywlgscg:'',
            hwbq:'',
            sfdyhwbq:'',
            title:'',
            zrtw:'',
            dyxw:'',
            xxf:'',
            sfdyxxf:''
        };
        $scope.changeZrtw=function(val) {
            if (val.length == 40) {
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "已超出限定字数",
                    duration: 1500
                });
            }
        };
        //返回保存设置
        $scope.saveSettings=function(){
            if($scope.print.fhrcg==true){
                $scope.print.sfdyfhrcg='1';
            }else if($scope.print.fhrcg==false){
                $scope.print.sfdyfhrcg='0';
            }
            if($scope.print.wlgscg==true){
                $scope.print.sfdywlgscg='1';
            }else if($scope.print.wlgscg==false){
                $scope.print.sfdywlgscg='0';
            }
            if($scope.print.hwbq==true){
                $scope.print.sfdyhwbq='1';
            }else if($scope.print.hwbq==false){
                $scope.print.sfdyhwbq='0';
            }
            if($scope.print.xxf==true){
                $scope.print.sfdyxxf='1';
            }else if($scope.print.xxf==false){
                $scope.print.sfdyxxf='0';
            }
            var dyType=$("#hwdyxw option:selected").val();
            console.log(dyType);
            PrinterFactory.saveSet(sid,user_id,yh_id,zd_id,$scope.print.sfdyfhrcg,$scope.print.sfdywlgscg,$scope.print.sfdyhwbq,$scope.print.title,$scope.print.kfdh,$scope.print.zrtw,dyType,$scope.print.sfdyxxf);
        };

        $scope.$on('Save.PrintSet',function(){
            var result=PrinterFactory.getResult();
            if(result.ACTION_RETURN_CODE=='000000'){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "打印设置已保存",
                    duration: 1500
                });
            }else {
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "打印设置保存失败",
                    duration: 1500
                });
            }
        });

        //初始化打印设置
        PrinterFactory.fetchPrint(sid,user_id,yh_id,zd_id);
        $scope.$on('Query.PrintSet',function(){
            var set=PrinterFactory.getSet();
            if(set.ACTION_RETURN_CODE=='000000'){
                var list=set.ACTION_INFO;
                if(list.sfdyfhrcg=='1'){
                    $scope.print.fhrcg=true;
                }else if(list.sfdyfhrcg=='0'){
                    $scope.print.fhrcg=false;
                }
                if(list.sfdyhwbt=='1'){
                    $scope.print.hwbq=true;
                }else if(list.sfdyhwbt=='0'){
                    $scope.print.hwbq=false;
                }
                if(list.sfdywlgscg=='1'){
                    $scope.print.wlgscg=true;
                }else if(list.sfdywlgscg=='0'){
                    $scope.print.wlgscg=false;
                }
                if(list.sfdyxxf=='1'){
                    $scope.print.xxf=true;
                }else if(list.sfdyxxf=='0'){
                    $scope.print.xxf=false;
                }
                $("#hwdyxw").val(list.hwbtdyxw);
                $scope.print.title=list.gsmc;
                $scope.print.zrtw=list.bz;
                $scope.print.kfdh=list.kfdh;
            }
        });
        //添加打印机
        $scope.scanLy=function(){
            $cordovaHdoitBle.scan();
        };
        $scope.myGoBack = function() {
            $ionicHistory.goBack();
        };
        //$scope.blueTooth={
        //    name:''
        //};

        $("#bluet").val("未连接蓝牙设备");
        function getBleName(){
            //蓝牙设备名称
            $cordovaHdoitBle.bluetoothName(function(success){
                if(success!=null){
                    $("#bluet").val(success+'已连接');
                }
                else {
                    $("#bluet").val("未连接蓝牙设备");
                }
            },function(err){
                if(err!=null){
                    $("#bluet").val(err);
                }
                else {
                    $("#bluet").val("未连接蓝牙设备");
                }
            });
        }
        window.setInterval(getBleName,1);
    })
    //意见反馈
    .controller('FeedbackCtrl',function($scope,$ionicLoading,$state,Storage,FeedbackFactory){
        var sid=Storage.get('sid');
        var user_id=Storage.get('user_id');
        var yh_id=Storage.get('yh_id');
        var lxdh=Storage.get('lxdh');
        var sfwlgs=Storage.get('sfwlgs');
        $scope.feedback={
            content:''
        };
        $scope.submitYj=function(content){
            if (content==''){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "请输入反馈内容",
                    duration: 1500
                });
            }else {
                FeedbackFactory.getcontent(sid,user_id,yh_id,lxdh,sfwlgs,content);
            }
        };
        $scope.$on('FeedbackData',function(){
            var result=FeedbackFactory.getResult();
            if (result==true){
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "感谢您的反馈",
                    duration: 1500
                });
                $state.go('settings');
            }else {
                $ionicLoading.show({
                    noBackdrop: true,
                    template: "提交失败",
                    duration: 1500
                });
            }
        });
    })

    //选择联系人
    .controller('LinkmanCtrl',function($scope,$ionicLoading,$state,Storage,LinkmanFactory,$ionicHistory,$stateParams,$ionicPopup){
        $scope.showloading=true;
        var sid=Storage.get('sid');
        var user_id=Storage.get('user_id');
        var yh_id=Storage.get('yh_id');
        var dw_id=Storage.get('dw_id');
        var htmlbs=$stateParams.htmlbs;
        var sflx=$stateParams.sflx;
        var khmc='';
        var lxdh='';
        var pyjm='';
        LinkmanFactory.getcontent(sid,user_id,yh_id,dw_id,sflx,khmc,lxdh,pyjm);
        $scope.$on('LinkmanList.linkUpdated',function(){
            var result=LinkmanFactory.getLinkman();
            $scope.linkmanData=result.data;
            console.log($scope.linkmanData);
            $scope.showloading=false;
        });
        //下拉更新
        $scope.doRefresh=function(){
            LinkmanFactory.getcontent(sid,user_id,yh_id,dw_id,sflx,khmc,lxdh,pyjm);
            $scope.$broadcast('scroll.refreshComplete');
        };
        //上拉更新
        $scope.loadMore=function(){
            LinkmanFactory.getMoreLink(sid,user_id,yh_id,dw_id,sflx,khmc,lxdh,pyjm);
            $scope.$broadcast('scroll.infiniteScrollComplete');
        };
        //下一页
        $scope.hasNextPage = function() {
            return LinkmanFactory.hasNextPage();
        };

        $scope.search={
            content:''
        };

        $scope.searchLinkman=function(val){
            var re = /^[0-9]+.?[0-9]*$/;
            var reg= /^[A-Za-z]+$/;
            if (re.test(val)){
                lxdh=val;
            }else if (reg.test(val)){
                pyjm=val.toUpperCase();
            }else {
                khmc=val;
            }
            LinkmanFactory.getcontent(sid,user_id,yh_id,dw_id,sflx,khmc,lxdh,pyjm);
        };

        $scope.chooseLinkman=function(khmc,lxdh){
            if(htmlbs==1){
                $state.go('addcyd',{khmc:khmc,lxdh:lxdh,sflx:sflx});
            }else if(htmlbs==2){
                $state.go('cydChange',{khmc:khmc,lxdh:lxdh,sflx:sflx});
            }else if (htmlbs==3){
                $state.go('searchkhdz',{khmc:khmc,lxdh:lxdh});
            }else if(htmlbs==4){
                $state.go('cydSearch',{khmc:khmc,lxdh:lxdh,sflx:sflx});
            }else if (htmlbs==5){
                $state.go('shrlistsearch',{khmc:khmc,lxdh:lxdh});
            }
        };
        //长按删除
        $scope.deleteLink=function(data){
            var receipt = $ionicPopup.confirm({
                title : '是否删除联系人',
                cancelText : '取消',
                cancelType : 'button-stable',
                okText : '删除'
            });
            receipt.then(function(r){
                if(r){
                    LinkmanFactory.getDelete(sid,user_id,dw_id,yh_id,data.kh_id);
                    $scope.$on('DeleteData',function(){
                        var result=LinkmanFactory.deleteResult();
                        if (result==1){
                            $ionicLoading.show({
                                noBackdrop: true,
                                template: "删除成功",
                                duration: 1500
                            });
                            $scope.linkmanData.splice($scope.linkmanData.indexOf(data), 1);
                        }else {
                            $ionicLoading.show({
                                noBackdrop: true,
                                template: "删除失败",
                                duration: 1500
                            });
                        }
                    });
                }else{
                    console.log('取消');
                }
            });
        };
        $scope.myGoBack = function() {
            $ionicHistory.goBack();
        };
    });
